<template>
  <div id="mapContainer"></div>

  <div class="panel">
    <el-button
      v-for="item in baseMaps"
      :key="item.id"
      @click="handlePickBaseMap(item)"
      >{{ item.name }}</el-button
    >
  </div>
</template>
<script setup>
import { Map, View } from "ol";
import { fromLonLat, get } from "ol/proj";

import { onMounted, nextTick, ref } from "vue";

import { tdt_api_key /** 天地图的key */ } from "@/config/keys.json";
import { addTdtBaseLayer } from "@/utils/baseMap.js";

function initMap() {
  const map = new Map({
    view: new View({
      center: fromLonLat([114.5, 31]),
      zoom: 9,
    }),
    target: "mapContainer",
  });

  // 加载底图
  addTdtBaseLayer(map, tdt_api_key, "img", "w", "wmts");

  window.map = map;
}

onMounted(() => {
  nextTick(() => {
    initMap();
  });
});

const baseMaps = ref([
  {
    id: "tdt_img_w",
    name: "天地图影像(EPSG:3857)",
    image: "/src/assets/images/baseMapPanel/tdt_img.png",
    default: true,
  },
  {
    id: "tdt_vec_w",
    name: "天地图矢量(EPSG:3857)",
    image: "/src/assets/images/baseMapPanel/tdt_vec.png",
  },
  {
    id: "tdt_ter_w",
    name: "天地图地形(EPSG:3857)",
    image: "/src/assets/images/baseMapPanel/tdt_ter.png",
  },
  {
    id: "tdt_img_c",
    name: "天地图影像(EPSG:4326)",
    image: "/src/assets/images/baseMapPanel/tdt_img.png",
  },
  {
    id: "tdt_vec_c",
    name: "天地图矢量(EPSG:4326)",
    image: "/src/assets/images/baseMapPanel/tdt_vec.png",
  },
  {
    id: "tdt_ter_c",
    name: "天地图地形(EPSG:4326)",
    image: "/src/assets/images/baseMapPanel/tdt_ter.png",
  },
]);

// 地图选择事件的回调
function handlePickBaseMap(item) {
  // 清除其它的底图
  window.map.getLayers().clear()
  // 加载新图层
  addTdtBaseLayer(
    window.map,
    tdt_api_key,
    item.id.split("_")[1],
    item.id.split("_")[2]
  );
}
</script>

<style scoped>
#mapContainer {
  width: 100%;
  height: 99vh;
}

.panel {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 999;
}
</style>
